package com.example.wwww.controller;

import com.example.wwww.model.User;
import com.example.wwww.repo.InMemoryStore;
import jakarta.validation.Valid;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@RequestMapping("/api/auth")
public class AuthController {
    private final InMemoryStore store;
    public AuthController(InMemoryStore store) { this.store = store; }

    @PostMapping("/login")
    public ResponseEntity<?> login(@RequestBody Map<String, String> payload) {
        String username = payload.get("username");
        String password = payload.get("password");
        String userType = payload.get("userType");
        return store.getUserByUsername(username)
                .filter(u -> password.equals(u.getPassword()) && (userType == null || userType.equals(u.getType())))
                .<ResponseEntity<?>>map(u -> ResponseEntity.ok(Map.of(
                        "id", u.getId(),
                        "username", u.getUsername(),
                        "phone", u.getPhone(),
                        "email", u.getEmail(),
                        "type", u.getType(),
                        "registerTime", u.getRegisterTime()
                )))
                .orElse(ResponseEntity.status(401).body(Map.of("message", "用户名或密码错误")));
    }

    @PostMapping("/register")
    public ResponseEntity<?> register(@Valid @RequestBody User user) {
        if (store.getUserByUsername(user.getUsername()).isPresent()) {
            return ResponseEntity.badRequest().body(Map.of("message", "用户名已存在"));
        }
        User created = store.addUser(user);
        return ResponseEntity.ok(created);
    }
}


